package com.fastbee.iot.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fastbee.common.core.domain.entity.SysRole;
import com.fastbee.common.core.domain.entity.SysUser;
import com.fastbee.common.utils.DateUtils;
import com.fastbee.common.utils.StringUtils;
import com.fastbee.framework.web.domain.server.Sys;
import com.fastbee.iot.domain.AlertLogEntity;
import com.fastbee.iot.domain.AlertLogPageDto;
import com.fastbee.iot.domain.DeviceLog;
import com.fastbee.iot.model.*;
import com.fastbee.iot.model.param.DataCenterParam;
import com.fastbee.system.domain.CommonStatistics;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fastbee.iot.mapper.AlertLogMapper;
import com.fastbee.iot.domain.AlertLog;
import com.fastbee.iot.service.IAlertLogService;

import static com.fastbee.common.utils.SecurityUtils.getLoginUser;

/**
 * 设备告警Service业务层处理
 *
 * @author kerwincui
 * @date 2022-01-13
 */
@Service
public class AlertLogServiceImpl implements IAlertLogService {
    @Autowired
    private AlertLogMapper alertLogMapper;

    /**
     * 查询设备告警
     *
     * @param alertLogId 设备告警主键
     * @return 设备告警
     */
    @Override
    public AlertLog selectAlertLogByAlertLogId(Long alertLogId) {
        return alertLogMapper.selectAlertLogByAlertLogId(alertLogId);
    }

    /**
     * 查询设备告警列表
     *
     * @param alertLog 设备告警
     * @return 设备告警
     */
    @Override
    public List<AlertLog> selectAlertLogList(AlertLog alertLog) {
        SysUser user = getLoginUser().getUser();
//        List<SysRole> roles = user.getRoles();
//        for (int i = 0; i < roles.size(); i++) {
//            // 租户和用户，只查看自己分组
//            if (roles.get(i).getRoleKey().equals("tenant") || roles.get(i).getRoleKey().equals("general")) {
//                alertLog.setUserId(user.getUserId());
//                break;
//            }
//        }
        // 查询所属机构
        // 兼容组态多租户分享
        if (null != alertLog.getDeptUserId()) {
            alertLog.setUserId(alertLog.getDeptUserId());
        } else {
            if (null != user.getDeptId()) {
                alertLog.setUserId(user.getDept().getDeptUserId());
            } else {
                alertLog.setUserId(user.getUserId());
            }
        }
        return alertLogMapper.selectAlertLogList(alertLog);
    }

    @Override
    public List<AlertLog> selectAlertLogListByCreateBy(String createBy, String remark, Integer status) {
        AlertLog alertLog = new AlertLog();
        alertLog.setCreateBy(createBy);
        alertLog.setStatus(status);
        alertLog.setRemark(remark);
        return alertLogMapper.selectAlertLogList(alertLog);
    }

    /**
     * 查询设备告警列表
     *
     * @param alertLog 设备告警
     * @return 设备告警
     */
    @Override
    public Long selectAlertLogListCount(AlertLog alertLog) {
//        SysUser user = getLoginUser().getUser();
//        List<SysRole> roles = user.getRoles();
//        for (int i = 0; i < roles.size(); i++) {
//            // 租户和用户，只查看自己分组
//            if (roles.get(i).getRoleKey().equals("tenant") || roles.get(i).getRoleKey().equals("general")) {
//                alertLog.setUserId(user.getUserId());
//                break;
//            }
//        }
        return alertLogMapper.selectAlertLogListCount(alertLog);
    }

    @Override
    public List<DeviceAlertCount> selectDeviceAlertCount() {
        return alertLogMapper.selectDeviceAlertCount();
    }

    @Override
    public DeviceAlertCount selectDeviceAlertCountBySN(String serialNumber) {
        return alertLogMapper.selectDeviceAlertCountBySN(serialNumber);
    }

    @Override
    public List<DeviceAlertCount> selectSceneAlertCount() {
        return alertLogMapper.selectSceneAlertCount();
    }

    @Override
    public DeviceAlertCount selectSceneAlertCountBySceneId(String sceneId) {
        return alertLogMapper.selectSceneAlertCountBySceneId(sceneId);
    }

    /**
     * 新增设备告警
     *
     * @param alertLog 设备告警
     * @return 结果
     */
    @Override
    public int insertAlertLog(AlertLog alertLog) {
        alertLog.setCreateTime(DateUtils.getNowDate());
        return alertLogMapper.insertAlertLog(alertLog);
    }

    @Override
    public int insertAlertLogBatch(List<AlertLog> alertLogList) {
        return alertLogMapper.insertAlertLogBatch(alertLogList);
    }

    /**
     * 修改设备告警
     *
     * @param alertLog 设备告警
     * @return 结果
     */
    @Override
    public int updateAlertLog(AlertLog alertLog) {
        alertLog.setUpdateTime(DateUtils.getNowDate());
        if (alertLog.getRemark().length() > 0) {
            // 1=不需要处理,2=未处理,3=已处理
            alertLog.setStatus(3);
        }
        return alertLogMapper.updateAlertLog(alertLog);
    }

    @Override
    public int updateAlertLogStatus(AlertLog alertLog) {
        alertLog.setUpdateTime(DateUtils.getNowDate());
        return alertLogMapper.updateAlertLogStatus(alertLog);
    }

    /**
     * 批量删除设备告警
     *
     * @param alertLogIds 需要删除的设备告警主键
     * @return 结果
     */
    @Override
    public int deleteAlertLogByAlertLogIds(Long[] alertLogIds) {
        return alertLogMapper.deleteAlertLogByAlertLogIds(alertLogIds);
    }

    /**
     * 删除设备告警信息
     *
     * @param alertLogId 设备告警主键
     * @return 结果
     */
    @Override
    public int deleteAlertLogByAlertLogId(Long alertLogId) {
        return alertLogMapper.deleteAlertLogByAlertLogId(alertLogId);
    }

    /**
     * 通过设备编号删除设备告警信息
     *
     * @param SerialNumber 设备告警主键
     * @return 结果
     */
    @Override
    public int deleteAlertLogBySerialNumber(String SerialNumber) {
        return alertLogMapper.deleteAlertLogBySerialNumber(SerialNumber);
    }
    @Override
    public List<AlertCountVO> countAlertProcess(DataCenterParam dataCenterParam) {
        return alertLogMapper.countAlertProcess(dataCenterParam);
    }

    @Override
    public List<AlertCountVO> countAlertLevel(DataCenterParam dataCenterParam) {
        return alertLogMapper.countAlertLevel(dataCenterParam);
    }

    @Override
    public Page<AlertLogEntity> getBigAlarmPage(AlertLogPageDto dto) {
        Page page = new Page();
        page.setSize(dto.getSize());
        page.setCurrent(dto.getCurrent());
        page.setSearchCount(true);
        AlertLogEntity alertLog = new AlertLogEntity();
        BeanUtils.copyProperties(dto,alertLog);


        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtil.offsetHour(new Date(),16));
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH)+1;
        Integer day = calendar.get(Calendar.DAY_OF_MONTH)+1;
        Integer lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        String startDate = "";
        String endDate = "";
        if(dto.getTypeId() == null){
            dto.setTypeId(3);
        }
        if(dto.getTypeId() == 1){
            startDate = year+"-01-01 00:00:00";
            endDate = year+"-12-31 23:59:59";
        }
        if(dto.getTypeId() == 2){
            startDate = year+"-"+month+"-01"+" 00:00:00";
            endDate = year+"-"+month+"-"+lastDay+" 23:59:59";
        }
        if(dto.getTypeId() == 3){
            int dayData = day;
            if(dayData > 1){
                dayData = (dayData -1);
            }
            startDate = year+"-"+month+"-"+dayData+" 00:00:00";
            endDate = year+"-"+month+"-"+day+" 23:59:59";
        }
        System.out.println("告警查询时间："+startDate+"-"+endDate);
        LambdaQueryWrapper<AlertLogEntity> query = new LambdaQueryWrapper<>(alertLog);
        if(StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)){
            query.ge(AlertLogEntity::getCreateTime,startDate);
            query.le(AlertLogEntity::getCreateTime,endDate);
        }
        query.orderByDesc(AlertLogEntity::getCreateTime);
        return alertLogMapper.selectPage(page,query);
    }

    @Override
    public BigScreenAlarmStatisVo getBigScreenAlarmStatisVo(CommonStatistics dto) {
        BigScreenAlarmStatisVo statisVo = new BigScreenAlarmStatisVo();
        statisVo = alertLogMapper.getBigScreenAlarmStatisVo(dto);
        return statisVo;
    }

    @Override
    public List<CommonStatisVo> selectRealEnergyAlarmMonitior(Integer typeId, List<String> serialNumbers, Date date) {
        List<CommonStatisVo> resultList = new LinkedList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH)+1;
        Integer day = calendar.get(Calendar.DAY_OF_MONTH)+1;
        Integer lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        String beginTime = year+"-01-01 00:00:00";
        String endTime = year+"-12-31 23:59:59";

        if(typeId == 2){
            beginTime = year+"-"+month+"-"+day+" 00:00:00";
            endTime = year+"-"+month+"-"+day+" 23:59:59";
        }else if(typeId == 3){
            beginTime = year+"-"+month+"-01"+" 00:00:00";
            endTime = year+"-"+month+"-"+lastDay+" 23:59:59";
        }else if(typeId == 4){
            beginTime = (year - 7)+"-01-01 00:00:00";;
            endTime = year+"-12-31 23:59:59";
        }

        List<CommonStatisVo> dataList = alertLogMapper.getALarmList(serialNumbers,beginTime,endTime,typeId);
        Map<String,List<CommonStatisVo>> dataMap = new HashMap<>();
        if(dataList.size() > 0){
            dataMap = dataList.stream().collect(Collectors.groupingBy(CommonStatisVo::getName));
        }
        if(typeId == 1){
            //年
            for (int i = 1; i < 13; i++) {
                CommonStatisVo vo = new CommonStatisVo();
                String key = i > 9 ? String.valueOf(i) : "0"+i;
                vo.setName(key+"月");
                vo.setValue(dataMap.get(key) != null ? dataMap.get(key).get(0).getValue(): BigDecimal.ZERO);
                resultList.add(vo);
            }
        } else if(typeId == 2){
            //月
            for (int i = 1; i < lastDay+1; i++) {
                CommonStatisVo vo = new CommonStatisVo();
                String key = i > 9 ? String.valueOf(i) : "0"+i;
                vo.setName(key);
                vo.setValue(dataMap.get(key) != null ? dataMap.get(key).get(0).getValue(): BigDecimal.ZERO);
                resultList.add(vo);
            }
        } else if(typeId == 3){
            //日
            for (int i = 1; i < 25; i++) {
                CommonStatisVo vo = new CommonStatisVo();
                String key = i > 9 ? String.valueOf(i) : "0"+i;
                vo.setName(key);
                vo.setValue(dataMap.get(key) != null ? dataMap.get(key).get(0).getValue(): BigDecimal.ZERO);
                resultList.add(vo);
            }
        }else{
            //近七年

        }
        return resultList;
    }
}
